<?php
	set_time_limit(60*60);
	ini_set('memory_limit', '128M');

	require_once "config.php";
	require_once dirname(__FILE__). '/util/connection.class.php';
	require_once dirname(__FILE__). '/util/TimeUtil.php';
	
	$dbconn = Connection::getInstance();
	
	$processAll = false;
	
	if (isset($argv[1]) && $argv[1] == 'all') {
		$processAll = true;
	}
	
	if (!$processAll) {
		// get users have finished offer in the last hour
		$now = time();
		$time = $now - $now % (60*60) - $aheadHours * 60*60;
		$lastHour = date('Y-m-d H:i:s', $time);
		
		$sql = 'select distinct user_id from rewards where created_date >= ?';
		$userIdsResult = $dbconn->query($sql, array($lastHour));
	} else {
		$sql = 'select distinct user_id from rewards';
		$userIdsResult = $dbconn->query($sql);
	}
	
	$userIds = array();
	$totalIdAmount = count($userIdsResult);
	if ($totalIdAmount) {
		foreach ($userIdsResult as $userIdResult) {
			$userIds[] = $userIdResult['user_id'];
		}
		
		$fragment = 0;
		while (true) {
			if ($totalIdAmount > 100) {
				$processUserIds = array_slice($userIds, $fragment * 100, 100);
				updateUserAllinboxStatus($processUserIds, $dbconn);
				$totalIdAmount -= 100;
				++$fragment;
				continue;
			} else {
				$processUserIds = array_slice($userIds, $fragment * 100);
				if (count($processUserIds) > 0) {
					updateUserAllinboxStatus($processUserIds, $dbconn);
				}
				break;
			}
		}
		
	}
	
	
	
	
	
	
	
	
	function updateUserAllinboxStatus(array $ids, $dbconn) {
		$sql = "update allinbox_subscriber set status = 'unsub' where status = 'sub' and user_id in (" . implode(' ,', $ids) . ')';
		return $dbconn->execute($sql);
	}
	
	
	